<template>
  <el-button style="margin: 10px 0 10px 10px" type="primary" @click="showDeployDialog">部署流程</el-button>
  <el-table :data="workflowDefList" border style="width: 100%">
    <el-table-column label="流程Key" prop="processKey" width="180"/>
    <el-table-column label="流程名" prop="processName" width="180"/>
    <el-table-column label="流程最新版本" prop="processVersion"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button @click="handleStartProcess(scope.row.processKey)">发起流程</el-button>
        <el-button type="success" @click="handleProcessConfig(scope.row.processKey)">流程配置</el-button>
        <el-button type="danger" @click="deleteDeployment(scope.row.processKey)">删除部署</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--  开启流程时，设置网关等变量-->
  <el-dialog v-model="showVariableDialogVisible" class="variable-dialog" title="请填写流程变量">
    <div class="dialog-body">
      <el-card class="form-card">
        <el-form label-position="left" label-width="120px">
          <span>是否跳过第一个节点： </span>
          <el-switch
              v-model="skipFirstFlag"
              active-text="是"
              inactive-text="否"
              inline-prompt
          />
          <el-form-item class="custom-form-item">
            <template #label>
              <el-tooltip
                  content="业务键"
                  effect="light"
                  placement="top"
                  popper-class="custom-tooltip"
              >
                <span class="variable-label">businessKey</span>
              </el-tooltip>
            </template>
            <el-input
                v-model="businessKey"
                class="custom-input"
                clearable
                style="width: 300px;"
            ></el-input>
          </el-form-item>
          <div v-for="item in variableList" :key="key" class="form-item">
            <el-form-item class="custom-form-item">
              <template #label>
                <el-tooltip
                    :content="item.nodeName"
                    effect="light"
                    placement="top"
                    popper-class="custom-tooltip"
                >
                  <span class="variable-label">{{ item.nodeVariable }}</span>
                </el-tooltip>
              </template>
              <el-input
                  v-model="variableFormData[item.nodeVariable]"
                  :disabled="!isBlank(item.variableValue) "
                  class="custom-input"
                  clearable
                  style="width: 300px;"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>

        <div class="form-actions">
          <el-button
              class="submit-btn"
              type="primary"
              @click="handleConfirmStartProcess"
          >
            确定
          </el-button>
          <el-button class="reset-btn" @click="showVariableDialogVisible = false">取消</el-button>
        </div>
      </el-card>

    </div>
  </el-dialog>

  <!--  流程配置使用-->
  <el-dialog v-model="showVariableDialogVisible2" class="variable-dialog" title="请配置流程节点审批人">
    <div class="dialog-body">
      <el-card class="form-card">
        <el-form label-position="left" label-width="120px">
          <div v-for="item in flowVariableList" :key="key" class="form-item">
            <el-form-item class="custom-form-item">
              <template #label>
                <el-tooltip
                    :content="item.nodeName"
                    effect="light"
                    placement="top"
                    popper-class="custom-tooltip"
                >
                  <span class="variable-label">{{ item.nodeVariable }}</span>
                </el-tooltip>
              </template>
              <el-select
                  v-model="item.assignUserId"
                  placeholder="Select"
                  size="large"
                  style="width: 240px"
                  @change="handleSelectedChange(item)"
              >
                <el-option
                    v-for="item in sysUserList"
                    :key="item.userId"
                    :label="item.nickname"
                    :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-form>

        <div class="form-actions">
          <el-button
              class="submit-btn"
              type="primary"
              @click="handleConfirmUpdateFlowConfig"
          >
            确定
          </el-button>
          <el-button class="reset-btn" @click="showVariableDialogVisible2 = false">取消</el-button>
        </div>
      </el-card>

    </div>
  </el-dialog>

  <!-- 新增部署流程对话框 -->
  <el-dialog v-model="deployDialogVisible" title="部署流程" width="500px">
    <el-radio-group v-model="deployType">
      <el-radio :value="0">路径部署</el-radio>
      <el-radio :value="1">文件部署</el-radio>
    </el-radio-group>
    <el-form :model="deployForm" label-width="100px">

      <el-form-item label="流程名称">
        <el-input v-model="deployForm.processName" placeholder="请输入流程名称"></el-input>
      </el-form-item>

      <div v-if="deployType === 0">
        <el-form-item label="流程资源路径">
          <el-input v-model="deployForm.resourcePath" placeholder="请输入流程资源路径"></el-input>
        </el-form-item>
      </div>
      <div v-if="deployType === 1">
        <el-form-item>
          <span>请选择BPMN2.0 格式的xml 文件</span>
        </el-form-item>
        <el-form-item label="流程文件">
          <el-upload
              :auto-upload="false"
              :file-list="xmlFileList"
              :limit="1"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              action="#"
              class="upload-demo"
          >
            <el-button slot="trigger" size="small" type="primary">选取</el-button>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deployDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDeployConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script lang="ts" setup>

import {onMounted, ref} from "vue";
import {
  deleteDeployByProcessId,
  getWorkflowDefList, newFlowInstance,
} from "@/api/workflow/flowInstance";
import {message} from "@/utils/ElmessasgeUtils";
import {
  deployFlowViaXmlFile,
  deployFlowViaXmlPath,
  getAssignFlowVaries,
  getGateWayFlowVaries, saveOrUpdateBatchProcessAssignVariable
} from "@/api/workflow/process";
import {isBlank} from "@/utils/StringUtils"
import {getAllUserList} from "@/api/system/sysUser";
import {UploadFile} from "element-plus";

const showVariableDialogVisible = ref(false);
const showVariableDialogVisible2 = ref(false);

const variableList = ref([])
const variableFormData = ref({})

const skipFirstFlag = ref(true)

// 从后端获取的原始配置
const flowVariableList = ref([])

const workflowDefList = ref([])
const selectedProcessKey = ref("")

const businessKey = ref("")

const deployType = ref(0)

function handleSelectedChange(item: any) {
  let find = sysUserList.value.find(it => it.userId == item.assignUserId);
  item.assignUserName = find.username;
  item.assignUserNickName = find.nickname
}

function handleProcessConfig(processKey: string) {

  // 获取分配人配置
  getAssignFlowVaries(processKey).then((res: any) => {
    if (res.data.code === 200) {
      selectedProcessKey.value = processKey
      flowVariableList.value = res.data.data
      console.log('从后端获取的配置列表： ', flowVariableList.value)

      showVariableDialogVisible2.value = true
    } else {
      message("获取流程变量失败： " + res.data.message, "error")
    }

  })
}

function handleConfirmUpdateFlowConfig() {
  console.log('提交配置', flowVariableList.value)
  saveOrUpdateBatchProcessAssignVariable(flowVariableList.value).then((res: any) => {
    if (res.data.code === 200) {
      message("保存流程变量成功")
      showVariableDialogVisible2.value = false
    } else {
      message("保存流程变量失败： " + res.data.message, "error")
    }
  })

}

function handleStartProcess(processKey: string) {

  getGateWayFlowVaries(processKey).then((res: any) => {
    if (res.data.code === 200) {
      selectedProcessKey.value = processKey
      variableList.value = res.data.data

      console.log('variableList', variableList.value)

      variableList.value.forEach((item) => {
        variableFormData.value[item.nodeVariable] = item.assignUserId
      })

      showVariableDialogVisible.value = true
    } else {
      message("获取流程变量失败： " + res.data.message, "error")
    }

  })
}

function handleConfirmStartProcess() {
  showVariableDialogVisible.value = false

  console.log('selectedProcessKey', selectedProcessKey.value)
  console.log('variableFormData', variableFormData.value)
  console.log('skipFirstFlag', skipFirstFlag.value)

  // 根据流程定义Key发起流程
  newFlowInstance({
    processKey: selectedProcessKey.value,
    map: variableFormData.value,
    skipFirst: skipFirstFlag.value,
    businessKey: businessKey.value
  })
      .then((res: any) => {
        if (res.data.code === 200) {
          message("发起流程成功", "success")
          updateWorkflowDefList();
        } else {
          message("发起流程失败： " + res.data.msg, "error")
        }
      })

}

// 删除流程部署
function deleteDeployment(processId: string) {
  deleteDeployByProcessId(processId).then((res: any) => {
    if (res.data.code === 200) {
      updateWorkflowDefList();
    } else {
      message("删除流程部署失败： " + res.data.message, "error")
    }
  })
}

// 刷新流程定义列表
async function updateWorkflowDefList() {
  await getWorkflowDefList().then(res => {
    if (res.data.code === 200) {
      workflowDefList.value = res.data.data;
    } else {
      message("获取流程定义列表失败： " + res.data.message, "error")
    }

  })
}


function handleFileChange(file: any, fileList: any[]) {
  deployForm.value.xmlFile = file
  console.log("文件列表改变", deployForm.value.xmlFile)
}

function handleFileRemove(file: any, fileList: any[]) {
  deployForm.value.xmlFile = null
  console.log("文件列表移除", deployForm.value.xmlFile)
}

const sysUserList = ref([])
const xmlFileList = ref<UploadFile | null []>()

type DeployForm = {
  resourcePath: string,
  processName: string,
  xmlFile: UploadFile | null
}

// 新增部署流程相关数据和方法
const deployDialogVisible = ref(false)
const deployForm = ref<DeployForm>()

function showDeployDialog() {
  deployForm.value = {
    resourcePath: '',
    processName: '',
    xmlFile: null
  }
  deployDialogVisible.value = true
}

async function handleDeployConfirm() {

  let res: any;
  // 通过xml路径部署流程
  if (deployType.value === 0) {
    res = await deployFlowViaXmlPath(deployForm.value.resourcePath, deployForm.value.processName);
  }
  // 通过xml文件部署流程
  else {
    // xml文件不能为空
    if (!(deployForm.value.xmlFile) || !(deployForm.value.xmlFile.raw)) {
      message("请选择xml文件", "error")
      return
    }
    const formData = new FormData();
    formData.append('file', deployForm.value.xmlFile.raw);

    res = await deployFlowViaXmlFile(formData, deployForm.value.processName);
  }

  if (res.data.code === 200) {
    message("部署流程成功", "success")
    deployDialogVisible.value = false
  } else {
    message("部署流程失败： " + res.data.msg, "error")
  }

}


onMounted(async () => {
  await updateWorkflowDefList()

  await getAllUserList().then((res: any) => {
    if (res.data.code === 200) {
      sysUserList.value = res.data.data;
      console.log("sysUserList", sysUserList.value)
    } else {
      message("获取用户列表失败： " + res.data.message, "error")
    }
  })
})


</script>
<style scoped>

/* 对话框整体样式 */
.variable-dialog {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 对话框内容区域 */
.dialog-body {
  display: flex;
  justify-content: center;
}

.input-group label {
  display: inline-block;
  width: 200px;
  margin-right: 10px;
}

.input-group input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>